package com.sgb.member.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.member.MemberConfig;
import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentMemberBusinessChildBinding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.MaterialFilterJson;
import com.sgb.member.entity.PromotionInfoBean;
import com.sgb.member.ui.activity.PromotionInfoActivity;
import com.sgb.member.ui.adapter.PromotionInfoAdapter;
import com.sgb.member.view_model.PromotionInfoModel;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.view.selection.XChooseDialog;
import com.swgk.core.view.selection.XChooseEntity;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

// 会员经营商品
public class PromotionInfoFragment extends AppLazyFragment implements MemberStatusView.OnChooseListener, XChooseDialog.DialogCallBackImpl {

    @Inject
    public PromotionInfoModel sModel;
    private FragmentMemberBusinessChildBinding mBinding;
    private PromotionInfoAdapter mAdapter;
    private String mNo0 = ""; // "行业");
    private String mNo1 = ""; // "类型");
    private String mNo2 = ""; // "类别");
    private String mNo3 = ""; // "品名");
    private String mNo4 = ""; // "品名");
    private List<String> mNo41 = new ArrayList<>(); // 其他参数
    private String mNo5 = ""; // "经营地址");
    private String mNo51 = ""; // "经营地址");
    private String mNo6 = ""; // "距离");
    private String mNo7 = ""; // "价格排序");
    private int mCurPos; // 主页面TAB下标
    private CommonPopEntity mCurEntity; //主页面顶部点击对象

    // 经营地址Popup
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    private boolean noMoreData;

    public static PromotionInfoFragment newInstance(int position, CommonPopEntity entity) {
        PromotionInfoFragment fragment = new PromotionInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("INDEX", position);
        bundle.putSerializable("ENTITY", entity);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_member_business_child, container, false);
        mBinding.setLifecycleOwner(this);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        mCurPos = getArguments().getInt("INDEX", 0);
        mCurEntity = (CommonPopEntity) getArguments().getSerializable("ENTITY");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.chooseLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < mNameArray.size(); i++) {
                    XChooseEntity chooseEntity = mData.get(mData.keyAt(i));
                    if (chooseEntity != null) {
                        if (chooseEntity.getList() == null || chooseEntity.getList().size() == 0) {
                            if (chooseEntity.getSort() == PickCateType.TYPE_1 ||
                                    chooseEntity.getSort() == PickCateType.TYPE_5 ||
                                    chooseEntity.getSort() == PickCateType.TYPE_7) {
                                loadOtherData();
                                return;
                            }
                        }
                    }
                }
                mChooseDialog.initData(mData, mFilters);
                mChooseDialog.showDialog();
            }
        });
        mNo0 = mCurEntity.getId();
        initChooseDialog();
        initPopup();
        initRecycler();
    }

    @Override
    protected void onLazyLoad() {
        loadData(false);
        loadOtherData();
    }

    public void loadData(boolean isLoadMore) {
        if (isLoadMore && noMoreData) {
            closeRecyclerRefreshing();
            return;
        }
        String text = ((PromotionInfoActivity) getActivity()).getSearchText();
        sModel.getPromotionInfo(isLoadMore, text, mNo0, mNo1, mNo2, mNo3, mNo4, mNo41, mNo5, mNo51, mNo6, mNo7);
    }

    private void loadOtherData() {
        if (isListEmpty(PickCateType.TYPE_1)) {
            sModel.getFirstCategory(PickCateType.TYPE_1, mNo0, false); // 行业分类
        }
        if (isListEmpty(PickCateType.TYPE_5)) {
            sModel.getAddressModel(PickCateType.TYPE_5);  // 经营地址
        }
//        if (isListEmpty(PickCateType.TYPE_6)) {
//            sModel.getDistanceData(PickCateType.TYPE_6); // 距离
//        }
        if (isListEmpty(PickCateType.TYPE_7)) {
            sModel.getPriceData(PickCateType.TYPE_7); // 价格排序
        }
    }

    public void setAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            if (TextUtils.isEmpty(mNo6)) {
                mAddressPop.setData(data, true);
            } else {
                mAddressPop.setDataAndPosition(data, mNo6, mNo7, "", true, true);
            }
        } else {
            sModel.getAddressModel(PickCateType.TYPE_6);
        }
    }

    /**
     * -------------------------------------initRecycler------------------------------------------
     */
    private void initRecycler() {
        TextView textView = mBinding.emptyView.findViewById(R.id.no_data_count);
        textView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setPullRefreshEnabled(true);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBinding.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });
        initRecyclerAdapter(0);
    }

    private void initRecyclerAdapter(int index) {
        // 会员商品
        mAdapter = new PromotionInfoAdapter(getActivity(), null);
        mAdapter.setOnItemClick(new AdapterOnItemClick<PromotionInfoBean>() {
            @Override
            public void onItemClick(PromotionInfoBean goodsListEntity, int position) {
                // 商砼 == 7
                if ("7".equals(mNo1)) {
                    MaterialFilterJson filterJson = new MaterialFilterJson();
                    filterJson.setStrengthId(goodsListEntity.getSort());
                    MemberConfig.getInstance().startConcreteDetail(getActivity(), goodsListEntity.getId(), filterJson);
                } else {
                    MemberConfig.getInstance().startShopGoodsDetail(getContext(), goodsListEntity.getId(), "", goodsListEntity.getSkuid());
                }
            }
        });
        mBinding.recyclerView.setAdapter(mAdapter);
    }

    public void closeRecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void showEmpty() {
        mAdapter.clearDatas();
        mBinding.emptyView.setVisibility(View.VISIBLE);
    }

    public void refreshRecycler(List<PromotionInfoBean> list, boolean isLoadMore, boolean noMoreData) {
        mBinding.recyclerView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setLoadingMoreEnabled(!noMoreData);
        closeRecyclerRefreshing();
        this.noMoreData = noMoreData;
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                mAdapter.addDatas(list);
            }
        } else {
            if (list != null && list.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * ------------------------------- Popup ---------------------------------------------
     */
    private void initPopup() {
        mBinding.popup1.setKeyName("商品类型");
        mBinding.popup2.setKeyName("价格排序");
        mBinding.popup3.setKeyName("经营地址");
        mBinding.popup1.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popup2.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        initAddressPopup();
    }

    private void initAddressPopup() {
        mBinding.popup3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null) {
                    sModel.getAddressModel(PickCateType.TYPE_5);
                    return;
                }
                mBinding.popLine.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(mNo5) || !TextUtils.isEmpty(mNo51)) {
                    mBinding.popup3.updateChooseTextStatus(-2, null);
                } else {
                    mBinding.popup3.updateChooseTextStatus(-1, mBinding.popup3.getKeyName());
                }
                mAddressPop.showPopwindow0(mBinding.popLine);
            }
        });
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                mNo5 = "";
                mNo51 = "";
                mFilters.put(PickCateType.TYPE_5, 0);
                addMainEntity(PickCateType.TYPE_51, new ArrayList<>());
                mBinding.popup3.updateChooseTextStatus(0, mBinding.popup3.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    mNo5 = entity.getProvinceNo();
                    mBinding.popup3.updateChooseTextStatus(1, entity.getProvinceName());
                    mFilters.put(PickCateType.TYPE_5, mAddressPop.getProvincePosition());
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        mBinding.popup3.updateChooseTextStatus(1, entity.getCityName());
                        sModel.getAddressCityData(scrData, mNo5, PickCateType.TYPE_51, false);
                        mFilters.put(PickCateType.TYPE_51, mAddressPop.getmCityPosition());
                    }
                }
                //刷新数据
                loadData(false);
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            mBinding.popLine.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(mNo5) || !TextUtils.isEmpty(mNo51)) {
                mBinding.popup3.updateChooseTextStatus(1, null);
            } else {
                mBinding.popup3.updateChooseTextStatus(0, mBinding.popup3.getKeyName());
            }
        });
    }

    @Override
    public void onLoadChooseData(String mKeyName) {
        switch (mKeyName) {
            case "商品类型":
                sModel.getFirstCategory(PickCateType.TYPE_1, mNo0, false);
                break;
            case "经营地址":
                sModel.getAddressModel(PickCateType.TYPE_5);
                break;
            case "价格排序":
                sModel.getPriceData(PickCateType.TYPE_7);
                break;
        }
    }

    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        String id = position == 0 ? "" : entity.getId();
        String name = position == 0 ? "" : entity.getTypeName();
        switch (mKeyName) {
            case "商品类型":
                if (!TextUtils.equals(id, mNo1)) {
                    mNo1 = id;
                    mFilters.put(PickCateType.TYPE_1, position);
                    loadData(false);
                    updateOneCategoryData(entity, position, false);
                }
                break;
            case "经营地址":
                if (!TextUtils.equals(no, mNo5)) {
                    mNo5 = no;
                    mFilters.put(PickCateType.TYPE_5, position);
                    loadData(false);
                }
                break;
            case "价格排序":
                if (!TextUtils.equals(id, mNo7)) {
                    mNo7 = id;
                    mFilters.put(PickCateType.TYPE_7, position);
                    loadData(false);
                }
                break;
        }
    }

    /**
     * ------------------------------------ 侧滑刷选 ----------------------------------------
     */

    private XChooseDialog mChooseDialog;
    // 数据集X
    private SparseArray<XChooseEntity> mData = new SparseArray<>();
    // 本地缓存筛选结果
    private SparseIntArray mFilters = new SparseIntArray();
    private SparseArray<String> mNameArray;
    // 存储品名关联数据index
    private List<Integer> mMultiKey;

    private void initChooseDialog() {
        mNameArray = new SparseArray<>();
        mNameArray.put(PickCateType.TYPE_0, "行业");
        mNameArray.put(PickCateType.TYPE_1, "类型");
        mNameArray.put(PickCateType.TYPE_2, "类别");
        mNameArray.put(PickCateType.TYPE_3, "品名");
        mNameArray.put(PickCateType.TYPE_4, "品牌");
        mNameArray.put(PickCateType.TYPE_5, "经营地址");
        mNameArray.put(PickCateType.TYPE_51, "市区");
        mNameArray.put(PickCateType.TYPE_6, "距离");
        mNameArray.put(PickCateType.TYPE_7, "价格排序");
        mMultiKey = new ArrayList<>();
        mChooseDialog = new XChooseDialog(getContext(), mNameArray);
        mChooseDialog.setCallBack(this);
        for (int i = 0; i < mNameArray.size(); i++) {
            int key = mNameArray.keyAt(i);
            addMainEntity(key, new ArrayList<>());
        }
    }

    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        addMainEntity(type, data);
        switch (type) {
            case PickCateType.TYPE_1:
                mBinding.popup1.setData(data, mNo1);
                break;
            case PickCateType.TYPE_5:
                mBinding.popup3.setData(data, mNo5);
                break;
            case PickCateType.TYPE_7:
                mBinding.popup2.setData(data, mNo7);
                break;
        }
    }

    public void showLeftDialog(int type, List<CommonPopEntity> data) {
        mChooseDialog.addEntity(type, data);
        mChooseDialog.showDialog();
    }

    public void setMultiChooseItemData(int type, List<CommonPopEntity> data, CommonPopEntity all) {
        if (data != null && data.size() > 0) {
            int multiIndex = getMultiKey();
            for (CommonPopEntity datum : data) {
                List<CommonPopEntity> children = datum.getChildren();
                if (children != null && children.size() > 0) {
                    multiIndex += 1;
                    children.add(0, all);
                    mNameArray.put(multiIndex, datum.getTypeName());
                    mChooseDialog.addEntity(multiIndex, datum.getTypeName(), children);
                    mMultiKey.add(multiIndex);
                }
            }
        }
        mChooseDialog.showDialog();
    }

    public void addMainEntity(int index, List<CommonPopEntity> list) {
        if (mData.get(index) != null) {
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    private boolean isListEmpty(int catType) {
        return mData.get(catType) != null &&
                (mData.get(catType).getList() == null || mData.get(catType).getList().size() == 0);
    }

    @Override
    public void loadChildData(XChooseEntity entity, int pos) {
        switch (entity.getSort()) {
            case PickCateType.TYPE_0:
                updateCategoryData(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_1:
                updateOneCategoryData(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_2:
                updateTwoCategoryData(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_3:
                updateThreeCategoryData(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_5:
                updateCityData(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
        }
    }

    private void updateCityData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        mChooseDialog.addEntity(PickCateType.TYPE_51, new ArrayList<>());
        if (pos > 0) {
            sModel.getAddressCityData(scrData, entity.getNo(), PickCateType.TYPE_51, isShowLeftDialog);
        }
    }

    /**
     * 更新类型相关数据集合
     */
    private void updateCategoryData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        List<CommonPopEntity> tempList = new ArrayList<>();
        mChooseDialog.addEntity(PickCateType.TYPE_1, tempList);
        mChooseDialog.addEntity(PickCateType.TYPE_2, tempList);
        mChooseDialog.addEntity(PickCateType.TYPE_3, tempList);
        mChooseDialog.addEntity(PickCateType.TYPE_4, tempList);
        for (Integer integer : mMultiKey) {
            mChooseDialog.addEntity(integer, tempList);
        }
        if (pos > 0) {
            sModel.getFirstCategory(PickCateType.TYPE_1, entity.getId(), isShowLeftDialog);
        }
    }

    /**
     * 更新类别相关数据集合
     */
    private void updateOneCategoryData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        List<CommonPopEntity> tempList = new ArrayList<>();
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_2, tempList);
            mChooseDialog.addEntity(PickCateType.TYPE_3, tempList);
            mChooseDialog.addEntity(PickCateType.TYPE_4, tempList);
            for (Integer integer : mMultiKey) {
                mChooseDialog.addEntity(integer, tempList);
            }
        } else {
            addMainEntity(PickCateType.TYPE_2, tempList);
            addMainEntity(PickCateType.TYPE_3, tempList);
            addMainEntity(PickCateType.TYPE_4, tempList);
            for (Integer integer : mMultiKey) {
                addMainEntity(integer, tempList);
            }
        }
        if (pos > 0) {
            sModel.getCategoryChoose(PickCateType.TYPE_2, entity.getId(), isShowLeftDialog);
        }
    }

    /**
     * 更新类别相关数据集合
     */
    private void updateTwoCategoryData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        List<CommonPopEntity> tempList = new ArrayList<>();
        mChooseDialog.addEntity(PickCateType.TYPE_3, tempList);
        mChooseDialog.addEntity(PickCateType.TYPE_4, tempList);
        for (Integer integer : mMultiKey) {
            addMainEntity(integer, tempList);
        }
        if (pos > 0) {
            sModel.getCategoryChoose(PickCateType.TYPE_3, entity.getId(), isShowLeftDialog);
        }
    }

    /**
     * 更新类别相关数据集合
     */
    private void updateThreeCategoryData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        mChooseDialog.addEntity(PickCateType.TYPE_4, new ArrayList<>());
        for (Integer integer : mMultiKey) {
            mChooseDialog.addEntity(integer, new ArrayList<>());
        }
        if (pos > 0) {
            sModel.getCateArguments(PickCateType.TYPE_4, entity.getId(), isShowLeftDialog);
        }
    }

    @Override
    public void result(SparseArray<XChooseEntity> data, SparseIntArray map) {
        mData = CopyUtils.deepPopEntityCopy(data);
        mFilters = map.clone();
        mNo41.clear();
        for (int i = 0; i < mData.size(); i++) {
            XChooseEntity entity = mData.get(mData.keyAt(i));
            int key = entity.getSort();
            int value = mFilters.get(key);
            switch (key) {
                case PickCateType.TYPE_0:
                    if (mCurPos == 0) {
                        mNo0 = entity.getItemId(value);
                    }
                    break;
                case PickCateType.TYPE_1:
                    mNo1 = entity.getItemId(value);
                    mBinding.popup1.refreshChoose(mNo1, entity.getItemName(value), value);
                    mBinding.popup1.setData(entity.getList(), mNo1);
                    break;
                case PickCateType.TYPE_2:
                    mNo2 = entity.getItemId(value);
                    break;
                case PickCateType.TYPE_3:
                    mNo3 = entity.getItemId(value);
                    break;
                case PickCateType.TYPE_4:
                    mNo4 = entity.getItemId(value);
                    break;
                case PickCateType.TYPE_5:
                    mNo5 = entity.getItemNo(value);
                    mBinding.popup3.refreshChoose(mNo5, entity.getItemName(value), value);
                    mAddressPop.setDefPosition(value, 0);
                    break;
                case PickCateType.TYPE_51:
                    mNo51 = entity.getItemNo(value);
                    mAddressPop.setDefPosition(mFilters.get(PickCateType.TYPE_5), value);
                    if (value > 0) {
                        mBinding.popup3.refreshChoose(mNo51, entity.getItemName(value), value);
                    }
                    break;
                case PickCateType.TYPE_6:
                    mNo6 = entity.getItemId(value);
                    break;
                case PickCateType.TYPE_7:
                    mNo7 = entity.getItemId(value);
                    mBinding.popup2.refreshChoose(mNo7, entity.getItemName(value), value);
                    break;
                default:
                    if (value > 0 && mMultiKey.contains(key)) {
                        mNo41.add(entity.getItemName(value));
                    }
                    break;
            }
        }
        loadData(false);
    }

    private int getMultiKey() {
        return PickCateType.TYPE_4 * 100;
    }

    @Override
    public void reset() {
        resetMainData();
        mChooseDialog.showDialog();
    }

    @Override
    public void onCancel() {
        mChooseDialog.initData(mData, mFilters);
    }

    private void resetMainData() {
        List<CommonPopEntity> tempList = new ArrayList<>();
        mChooseDialog.addEntity(PickCateType.TYPE_2, tempList);
        mChooseDialog.addEntity(PickCateType.TYPE_3, tempList);
        mChooseDialog.addEntity(PickCateType.TYPE_4, tempList);
        mChooseDialog.addEntity(PickCateType.TYPE_51, tempList);
        for (Integer integer : mMultiKey) {
            mChooseDialog.addEntity(integer, tempList);
        }
    }

}
